using EIMS.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using Microsoft.Extensions.Caching.Memory;

namespace EIMS.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IMemoryCache _cache;

        public HomeController(ILogger<HomeController> logger, IMemoryCache cache)
        {
            _logger = logger;
            _cache = cache;
        }

        [ResponseCache(Duration = 10, Location = ResponseCacheLocation.Any)]
        public IActionResult Index()
        {
            // 如果用户已登录，显示仪表板（这个不使用缓存，因为需要展示实时数据）
            if (User.Identity?.IsAuthenticated == true)
            {
                return View("Dashboard");
            }

            // 否则显示欢迎/登录页面（可以缓存）
            return View();
        }

        [ResponseCache(Duration = 86400)] // 24小时缓存
        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        
        // 仪表板数据API
        [HttpGet]
        [Route("api/dashboard/stats")]
        public IActionResult GetDashboardStats()
        {
            // 使用缓存减少不必要的计算
            var stats = _cache.GetOrCreate("DashboardStats", entry => 
            {
                entry.SlidingExpiration = TimeSpan.FromMinutes(5);
                
                // 模拟实际数据统计，实际项目中这里会从数据库获取
                return new
                {
                    EmployeeCount = 12,
                    CustomerCount = 24,
                    ProductCount = 50,
                    OrderCount = 16,
                    RecentOrders = new[]
                    {
                        new { Id = "ORD-2023-001", Customer = "客户 A", Date = "2023-06-01", Amount = 2300.00, Status = "已完成" },
                        new { Id = "ORD-2023-002", Customer = "客户 B", Date = "2023-06-02", Amount = 1500.00, Status = "处理中" },
                        new { Id = "ORD-2023-003", Customer = "客户 C", Date = "2023-06-03", Amount = 3700.00, Status = "已发货" },
                        new { Id = "ORD-2023-004", Customer = "客户 D", Date = "2023-06-04", Amount = 900.00, Status = "待付款" }
                    },
                    LowStockItems = new[]
                    {
                        new { Name = "商品 A", Status = "库存不足" },
                        new { Name = "商品 B", Status = "库存较低" },
                        new { Name = "商品 C", Status = "库存较低" },
                        new { Name = "商品 D", Status = "库存不足" }
                    }
                };
            });
            
            return Json(stats);
        }
    }
}
